// 游戏配置对象
const gameConfig = {
    easy: { rows: 9, cols: 9, mines: 10 },
    medium: { rows: 16, cols: 16, mines: 40 },
    hard: { rows: 16, cols: 30, mines: 99 }
};

// 游戏状态管理
const gameState = {
    currentLevel: 'easy',
    isFirstClick: true,
    isGameOver: false,
    startTime: null,
    timer: null,
    mineCount: 0,
    revealedCount: 0,
    gameStats: {
        wins: 0,
        losses: 0,
        bestTimes: {
            easy: Infinity,
            medium: Infinity,
            hard: Infinity
        }
    }
};

// DOM 元素缓存
const elements = {
    startScreen: document.getElementById('startScreen'),
    mine: document.getElementById('mine'),
    gameBox: document.querySelector('.gameBox'),
    timer: document.querySelector('.timer'),
    mineNum: document.querySelector('.mineNum'),
    tips: document.querySelector('.tips'),
    statsPanel: document.querySelector('.stats-panel'),
    statsContent: document.querySelector('.stats-content'),
    difficultyButtons: document.querySelectorAll('.difficulty-buttons button'),
    levelButtons: document.querySelectorAll('.level button'),
    startButton: document.querySelector('.start-button'),
    restartButton: document.querySelector('.restart-btn')
};

// 难度映射
const LEVEL_MAP = {
  '初级': 'easy',
  '中级': 'medium',
  '高级': 'hard'
};

// 游戏状态
const GAME_STATE = {
  PLAYING: 'playing',
  WON: 'won',
  LOST: 'lost'
};

class Minesweeper {
  constructor(level = 'easy') {
    this.config = gameConfig[level];
    this.rows = this.config.rows;
    this.cols = this.config.cols;
    this.mines = this.config.mines;
    this.squares = [];
    this.tds = [];
    this.surplusMine = this.mines;
    this.gameState = GAME_STATE.PLAYING;
    this.parent = document.querySelector('.gameBox');
    this.mineNumDom = document.querySelector('.mineNum');
    this.tipsDom = document.querySelector('.tips');
    this.firstClick = true;
    this.startTime = null;
    this.timer = null;
    
    this.init();
  }

  // 生成随机雷的位置
  randomNum() {
    const totalSquares = this.rows * this.cols;
    return Array.from({ length: totalSquares }, (_, i) => i)
      .sort(() => Math.random() - 0.5)
      .slice(0, this.mines);
  }

  // 初始化游戏
  init() {
    this.setupGame();
    this.createDom();
    this.setupEventListeners();
    this.updateMineCount();
    this.hideTips();
    this.hideStats();
    this.startTimer();
    this.updateStatsDisplay();
  }

  setupGame() {
    const minePositions = this.randomNum();
    this.squares = Array.from({ length: this.rows }, (_, i) =>
      Array.from({ length: this.cols }, (_, j) => {
        const position = i * this.cols + j;
        return {
          type: minePositions.includes(position) ? 'mine' : 'number',
          x: j,
          y: i,
          value: 0,
          revealed: false,
          flagged: false
        };
      })
    );
    this.updateNumbers();
  }

  // 更新数字
  updateNumbers() {
    this.squares.forEach((row, i) => {
      row.forEach((square, j) => {
        if (square.type === 'mine') {
          this.getAround(square).forEach(([y, x]) => {
            this.squares[y][x].value++;
          });
        }
      });
    });
  }

  // 获取周围方格
  getAround(square) {
    const { x, y } = square;
    const result = [];
    
    for (let i = -1; i <= 1; i++) {
      for (let j = -1; j <= 1; j++) {
        const newX = x + i;
        const newY = y + j;
        
        if (
          newX >= 0 && newX < this.cols &&
          newY >= 0 && newY < this.rows &&
          !(i === 0 && j === 0) &&
          this.squares[newY][newX].type !== 'mine'
        ) {
          result.push([newY, newX]);
        }
      }
    }
    
    return result;
  }

  // 创建DOM
  createDom() {
    const table = document.createElement('table');
    
    this.tds = Array.from({ length: this.rows }, (_, i) => {
      const tr = document.createElement('tr');
      const tds = Array.from({ length: this.cols }, (_, j) => {
        const td = document.createElement('td');
        td.dataset.x = j;
        td.dataset.y = i;
        tr.appendChild(td);
        return td;
      });
      table.appendChild(tr);
      return tds;
    });

    this.parent.innerHTML = '';
    this.parent.appendChild(table);
  }

  // 设置事件监听
  setupEventListeners() {
    this.parent.addEventListener('contextmenu', e => e.preventDefault());
    this.parent.addEventListener('click', e => this.handleClick(e));
    this.parent.addEventListener('contextmenu', e => this.handleRightClick(e));
    
    // 添加难度选择事件
    document.querySelectorAll('.level button').forEach(button => {
      button.addEventListener('click', () => {
        if (button.textContent === '重新开始') {
          this.restart();
        } else {
          // 更新按钮状态
          document.querySelectorAll('.level button').forEach(btn => {
            btn.classList.remove('active');
          });
          button.classList.add('active');
          
          // 切换难度
          const level = LEVEL_MAP[button.textContent];
          if (level) {
            this.changeLevel(level);
          }
        }
      });
    });
  }

  // 处理左键点击
  handleClick(e) {
    if (this.gameState !== GAME_STATE.PLAYING) return;
    
    const td = e.target.closest('td');
    if (!td || td.classList.contains('flag')) return;

    if (this.firstClick) {
      this.firstClick = false;
      this.startTime = Date.now();
    }

    const x = parseInt(td.dataset.x);
    const y = parseInt(td.dataset.y);
    const square = this.squares[y][x];

    if (square.type === 'mine') {
      this.gameOver(td);
    } else {
      this.revealSquare(square);
      this.checkWin();
    }
  }

  // 处理右键点击
  handleRightClick(e) {
    if (this.gameState !== GAME_STATE.PLAYING) return;
    
    const td = e.target.closest('td');
    if (!td || td.classList.contains('revealed')) return;

    const x = parseInt(td.dataset.x);
    const y = parseInt(td.dataset.y);
    const square = this.squares[y][x];

    if (!square.flagged && this.surplusMine > 0) {
      square.flagged = true;
      td.classList.add('flag');
      this.surplusMine--;
    } else if (square.flagged) {
      square.flagged = false;
      td.classList.remove('flag');
      this.surplusMine++;
    }

    this.updateMineCount();
    this.checkWin();
  }

  // 揭示方格
  revealSquare(square) {
    if (square.revealed || square.flagged) return;
    
    square.revealed = true;
    const td = this.tds[square.y][square.x];
    td.classList.add('revealed');
    
    if (square.value === 0) {
      td.classList.add('zero');
      this.getAround(square).forEach(([y, x]) => {
        this.revealSquare(this.squares[y][x]);
      });
    } else {
      td.classList.add(`number-${square.value}`);
      td.textContent = square.value;
    }
  }

  // 检查胜利
  checkWin() {
    const allRevealed = this.squares.every(row => 
      row.every(square => 
        square.type === 'mine' || square.revealed
      )
    );

    if (allRevealed) {
      this.gameState = GAME_STATE.WON;
      this.showTips('恭喜你，游戏胜利！');
      this.stopTimer();
      this.saveGameStats();
      this.showStats();
    }
  }

  // 游戏结束
  gameOver(clickedTd) {
    this.gameState = GAME_STATE.LOST;
    this.stopTimer();
    
    this.squares.forEach((row, i) => {
      row.forEach((square, j) => {
        const td = this.tds[i][j];
        if (square.type === 'mine') {
          td.classList.add('mine');
          if (td === clickedTd) {
            td.classList.add('redMine');
          }
        }
      });
    });

    this.showTips('游戏结束！');
    this.saveGameStats();
    this.showStats();
  }

  // 更新剩余雷数显示
  updateMineCount() {
    this.mineNumDom.textContent = this.surplusMine;
  }

  // 显示提示
  showTips(message) {
    this.tipsDom.textContent = message;
    this.tipsDom.style.display = 'block';
  }

  // 隐藏提示
  hideTips() {
    this.tipsDom.style.display = 'none';
  }

  // 开始计时器
  startTimer() {
    this.startTime = Date.now();
    this.timer = setInterval(() => {
      const elapsed = Math.floor((Date.now() - this.startTime) / 1000);
      document.querySelector('.timer').textContent = elapsed;
    }, 1000);
  }

  // 停止计时器
  stopTimer() {
    clearInterval(this.timer);
  }

  // 保存游戏统计
  saveGameStats() {
    const stats = {
      level: this.config,
      time: Math.floor((Date.now() - this.startTime) / 1000),
      result: this.gameState,
      date: new Date().toISOString()
    };

    const savedStats = JSON.parse(localStorage.getItem('minesweeperStats') || '[]');
    savedStats.push(stats);
    localStorage.setItem('minesweeperStats', JSON.stringify(savedStats));
    
    // 更新统计显示
    this.updateStatsDisplay();
  }

  // 显示统计面板
  showStats() {
    const statsPanel = document.querySelector('.stats-panel');
    statsPanel.style.display = 'block';
    this.updateStatsDisplay();
  }

  // 隐藏统计面板
  hideStats() {
    const statsPanel = document.querySelector('.stats-panel');
    statsPanel.style.display = 'none';
  }

  // 更新统计显示
  updateStatsDisplay() {
    const statsContent = document.querySelector('.stats-content');
    const savedStats = JSON.parse(localStorage.getItem('minesweeperStats') || '[]');
    
    if (savedStats.length === 0) {
      statsContent.innerHTML = '<div class="no-stats">暂无游戏记录</div>';
      return;
    }
    
    // 按日期排序，最新的在前面
    savedStats.sort((a, b) => new Date(b.date) - new Date(a.date));
    
    // 只显示最近的10条记录
    const recentStats = savedStats.slice(0, 10);
    
    statsContent.innerHTML = recentStats.map(stat => {
      const levelName = Object.entries(LEVEL_MAP).find(([_, value]) => 
        value === Object.keys(gameConfig).find(key => 
          gameConfig[key].rows === stat.level.rows && 
          gameConfig[key].cols === stat.level.cols && 
          gameConfig[key].mines === stat.level.mines
        )
      )?.[0] || '未知难度';
      
      const result = stat.result === GAME_STATE.WON ? '胜利' : '失败';
      const date = new Date(stat.date).toLocaleString();
      
      return `
        <div class="stat-item ${stat.result === GAME_STATE.WON ? 'win' : 'lose'}">
          <div>难度：${levelName}</div>
          <div>结果：${result}</div>
          <div>用时：${stat.time}秒</div>
          <div>时间：${date}</div>
        </div>
      `;
    }).join('');
  }

  // 重新开始
  restart() {
    this.gameState = GAME_STATE.PLAYING;
    this.firstClick = true;
    this.surplusMine = this.mines;
    this.stopTimer();
    this.init();
  }

  // 改变难度
  changeLevel(level) {
    this.config = gameConfig[level];
    this.rows = this.config.rows;
    this.cols = this.config.cols;
    this.mines = this.config.mines;
    this.restart();
  }
}

// 初始化开始游戏界面
function initStartScreen() {
  const startScreen = document.getElementById('startScreen');
  const gameContainer = document.getElementById('mine');
  const startButton = document.getElementById('startGame');
  const difficultyButtons = document.querySelectorAll('.difficulty-buttons button');
  
  let selectedLevel = 'easy';
  
  // 设置难度选择按钮
  difficultyButtons.forEach(button => {
    button.addEventListener('click', () => {
      // 移除其他按钮的active类
      difficultyButtons.forEach(btn => btn.classList.remove('active'));
      // 添加当前按钮的active类
      button.classList.add('active');
      // 更新选中的难度
      selectedLevel = button.dataset.level;
    });
  });
  
  // 设置开始游戏按钮
  startButton.addEventListener('click', () => {
    // 隐藏开始界面
    startScreen.style.display = 'none';
    // 显示游戏界面
    gameContainer.style.display = 'block';
    // 初始化游戏
    window.game = new Minesweeper(selectedLevel);
    window.game.init();
  });
  
  // 默认选中初级难度
  difficultyButtons[0].classList.add('active');
}

// 页面加载完成后初始化开始界面
document.addEventListener('DOMContentLoaded', initStartScreen);
